import BLELocker from '../../common/BLELocker.js';
import CONSTANT_DATA from '../../common/constant_data.js';
var common = require("../../common/common.js")
var commonUtil = require('../../utils/commonUtil');
var colonyBlue = require("../../pages/index/colony_blue.js");

var util = require("util.js");
var connetToDfu = require("connect-to-dfu.js");
var dfuUpgrade = require("dfu-upgrade.js");
var connectCmd = require("connect-cmd.js");
var conReq = require('../conReq.js')

var dfuDevName = "DfuTarg";
const app = getApp()

var isFindDev = false;
var isFindDevLog = true;
var isDfuFlg = false;
var isScanTimeout = true;

var scanRetryCount = 1;
//未发现任何设备的时候重试一次
var noFindOneRetryCount = 1;
var isAlreadyConnectedCount = 0;
var scanTimoutTimer = null;
var _AdapterRespTime = 5000;
var openBlueAdapterTimer = null;

var conShowViewCallback = null; // mark: 连接页面显示回调

var scanDevice = function scanDevice(mac) {
  console.log("开始扫描--->", mac);
  if (app.globalData.isLeaseCon) {
    app.globalData._that.setData({
      loading_show: true,
      loading_desc: '开始查找设备...',
      connectDesc: "开始查找设备...",
    })
  }
  isFindDev = false;
  app.globalData._that.data.upgradeSuc = null;
  console.log("开始打开适配器--->", mac);
  isAlreadyConnectedCount = 0;

  if (scanTimoutTimer) {
    clearTimeout(scanTimoutTimer);
    scanTimoutTimer = null;
  }

  wx.getBluetoothAdapterState({
    success: function (res) {
      if (res && res.discovering) {
        //正在搜索的取消搜索
        wx.stopBluetoothDevicesDiscovery({
          success(res) {}
        });
      }
      if (res && res.available) {
        connectBox(mac);
      } else {
        openAdapterConnectBox(mac);
      }
    },
    fail: function (err) {
      openAdapterConnectBox(mac);
    }
  })


}

//打开适配器后进行连接
function openAdapterConnectBox(mac) {
  wx.openBluetoothAdapter({
    success: function (res) {
      connectBox(mac)
    },
    fail: function (err) {
      var isGatewayCon = app.globalData._that && colonyBlue.isGatewayCon(app.globalData._that);
      colonyBlue.bleConFailMark();
      console.log("蓝牙适配器打开失败,重试扫描连接", err, isGatewayCon);
      if (isGatewayCon && !app.globalData.beforeConIsGateway) {
        let macAddr = mac.indexOf("DK") == 0 ? mac.substring(2) : mac;
        console.log("蓝牙适配器打开失败,直接走网关连接,mac=", macAddr);
        colonyBlue.connectDev(macAddr, app.globalData._that);
      } else { // mark: 打开适配器失败，蓝牙权限未打开
        app.globalData.beforeConIsGateway = false;
        let rst = app.globalData._that && typeof app.globalData._that.bleConAuthCheck == 'function' ? app.globalData._that.bleConAuthCheck() : 0
        if(rst > 0) {
        } else {
          if(typeof app.globalData._that.getBleFailShowObj == 'function') {
            let bleFailShow = app.globalData._that.getBleFailShowObj()
            bleFailShow.modalMsgShow()
          }
          let pile_id = app.globalData._that.data.pile_id ? 'Z' + app.globalData._that.data.pile_id : '';
          app.globalData._that.setData({
            openning_show: false,
            loading_show: false,
            modal: {
              modal_show: true,
              desc_mini: 'BT未打开' + pile_id + '(' + app.globalData._that.data.phoneInfo + '-' + CONSTANT_DATA.err_type.new_conf_open_adapter_fail + ')',
              desc: '请打开蓝牙后重试', //此处的文字在wxml页面有用到，如果变更的话wxml也要同步变更
              retryConnect: true
            }
          });
        }        
      }
    }

  })
}

//连接控制盒
function connectBox(mac) {
  wx.removeStorageSync('retryOpenBlueAdapterCount');
  if (app.globalData.isLeaseCon) {
    BLELocker.setIsOpenAdapterFlg(true);
    app.globalData._that.setData({
      loading_show: true,
      loading_desc: '蓝牙适配器开启成功',
      connectDesc: "蓝牙适配器开启成功",
    })
  }

  let device = getDevFromCacheByMac(mac);
  if (device && app.globalData.conRetryCount > 1) {
    console.log("从缓存获取到设备,直接进行连接", mac)
    executeCon(device, mac);
  } else {

    console.log("开始搜索设备---->");
    let that = app.globalData._that
    if(that && that.showStatInfo) {
      app.globalData._that.showStatInfo(that.data.statVal.discover)
    }
    
    startScanBlue(mac);

  }

}

function startScanBlue(blueName) {
  wx.getBluetoothDevices({
    success: function (res) {
      console.log(res)
      let devices = res.devices;
      devices.forEach(device => {
        console.log("蓝牙名：" + device.name)
        if (device.name == blueName || device.localName == blueName) {
          console.log("存在已搜索到的设备,关闭连接---->", blueName);
          let deviceId = device.deviceId;
          wx.closeBLEConnection({
            deviceId: deviceId,
            success: function (res) {},
            fail: function (err) {},
            complete: function () {}
          });
        }
      });
      setTimeout(() => {
        scanBlue(blueName);
      }, 100);
    }
  })
}

//未搜索到任何设备关闭搜索，同时关闭蓝牙适配器
function stopDiscoveryAndCloseAdapter() {
  if (wx.canIUse('offBluetoothDeviceFound')) {
    wx.offBluetoothDeviceFound(function () {
      console.log("取消监听")
    });
  }
  wx.stopBluetoothDevicesDiscovery({
    success: function (res) {},
    complete: function () {
      wx.closeBluetoothAdapter({
        success: function (res) {},
      });
    }
  });
  if (app.globalData._that) {
    if(typeof app.globalData._that.getBleFailShowObj == 'function') {
      let bleFailShow = app.globalData._that.getBleFailShowObj()
      bleFailShow.modalMsgShow()
    }
    let pile_id = app.globalData._that.data.pile_id ? 'Z' + app.globalData._that.data.pile_id : '';
    app.globalData._that.setData({
      openning_show: false,
      loading_show: false,
      modal: {
        modal_show: true,
        desc_mini: '搜索不到任何设备,' + pile_id + '(' + app.globalData._that.data.phoneInfo + '-' + CONSTANT_DATA.err_type.new_con_scan_null + ')',
        desc: '请检查定位服务是否已打开',
        icon_name: 'icon-dingwei',
        desc_extra: '点击“打开定位方法”可查看图示指引',
        retryConnect: true,
        open_location_show: true,
      }
    });
    colonyBlue.bleConFailMark();
  } else {
    wx.showModal({
      title: '温馨提示',
      content: '请检查定位服务是否已打开',
    })
  }
}

//搜索蓝牙
function scanBlue(mac) {
  //扫描未收到任何设备的时长限制
  console.log('开始扫描--', scanRetryCount, scanTimoutTimer == null);
  clearTimeout(scanTimoutTimer);
  scanTimoutTimer = setTimeout(function () {
    colonyBlue.bleConFailMark();
    util.recordLog(CONSTANT_DATA.err_type.new_con_scan_null, "扫描api调用超时:" + mac + ":" + noFindOneRetryCount + ":" + scanRetryCount);
    if (wx.canIUse('offBluetoothDeviceFound')) {
      wx.offBluetoothDeviceFound(function () {
        console.log("取消监听")
      });
    }
    common.locationAddr(function(res){
      let data = res ? JSON.stringify(res) : "";
      util.recordLog(CONSTANT_DATA.err_type.scan_no_dev_timeout_location_suc, "获取定位成功:" + mac + ":" + data + ":" + noFindOneRetryCount);
      if (noFindOneRetryCount > 0) {
        noFindOneRetryCount--;
        wx.stopBluetoothDevicesDiscovery({
          success: function (res) {},
          complete: function () {
            scanDevice(mac);
          }
        });
        if (app.globalData.isLeaseCon) {
          app.globalData._that.setData({
            loading_show: true,
            loading_desc: '重新查找设备...',
            connectDesc: "重新查找设备...",
          })
        }
      } else {
        stopDiscoveryAndCloseAdapter();
      }
    }, function(err){
      let errInfo = res ? JSON.stringify(err) : "";
      util.recordLog(CONSTANT_DATA.err_type.scan_no_dev_timeout_location_fail, "获取定位失败:" + mac + ":" + errInfo);
      stopDiscoveryAndCloseAdapter();
    }) 
  }, 5000);

  wx.startBluetoothDevicesDiscovery({
    // services: ["FEE7"],//过滤，只搜索微信硬件设备
    allowDuplicatesKey: true,
    interval: 0.1,
    powerLevel: 'high',
    success: function (res) {
      console.log("开始扫描设备...." + mac, res);
      if (app.globalData.isLeaseCon) {
        app.globalData._that.setData({
          loading_show: true,
          loading_desc: '在附近查找设备中...',
          connectDesc: "在附近查找设备中...",
        })
      }

      bleCallback(mac);

      if (getApp().globalData.isBeforeLeaseUpgrade) {
        wx.showLoading({
          title: '扫描中..',
          mask: true
        });
      }
    },
    fail: function (err) {
      console.log("扫描打开失败", err);
      let failDesc = "搜索启动失败:" + (err ? JSON.stringify(err) : "null");
      util.recordLog(CONSTANT_DATA.err_type.connect_scan_fail, failDesc);

      clearTimeout(scanTimoutTimer);

      if (app.globalData.isLeaseCon) {
        app.globalData._that.setData({
          loading_show: true,
          loading_desc: '查找设备启动失败,请重新扫码',
          connectDesc: "查找设备启动失败,请重新扫码",
        })
        setTimeout(function () {
          app.globalData._that.setData({
            loading_show: false,
          })
        }, 1500);
      }
    }
  })
}

function bleCallback(mac) {
  console.log("开始接收上报设备:", mac)
  getApp().globalData.scanEquTimer = setTimeout(function () {

    if (app.globalData.isLeaseCon) {
      let descStr = !app.globalData.isFindTimeout ? '发现设备超时,重试中...' : '发现设备超时,请确认再设备旁,再扫码重试下';
      app.globalData._that.setData({
        loading_show: true,
        loading_desc: descStr,
        connectDesc: descStr,
      })

      if (app.globalData.isFindTimeout) {
        util.recordLog(CONSTANT_DATA.err_type.connect_scan_find_timeout, "发现设备超时:" + mac);
        stopDiscoveryAndCloseAdapter();
        setTimeout(function (res) {
          app.globalData._that.setData({
            loading_show: false
          })
        }, 1500);
      } else {
        app.globalData.isFindTimeout = true;
        if (wx.canIUse('offBluetoothDeviceFound')) {
          wx.offBluetoothDeviceFound(function () {
            console.log("取消监听")
          });
        }
        wx.stopBluetoothDevicesDiscovery({
          success: function (res) {

            wx.closeBluetoothAdapter({
              success: function (res) {
                setTimeout(function (res) {
                  wx.openBluetoothAdapter({
                    success: function (res) {
                      getApp().globalData.scanEquTimer = setTimeout(function (res) {
                        scanBlue(mac);
                        util.recordLog(CONSTANT_DATA.err_type.connect_scan_find_retry, "发现设备超时重试:" + mac);
                      }, 10000);
                    },
                    fail: function (err) {
                      app.globalData._that.setData({
                        loading_show: false
                      });
                      wx.showToast({
                        title: '扫重试03',
                      })
                    }
                  })
                }, 500);
              },
              fail: function (err) {
                app.globalData._that.setData({
                  loading_show: false
                });
                wx.showToast({
                  title: '扫重试02',
                })
              }
            });

          },
          fail: function () {
            app.globalData._that.setData({
              loading_show: false
            });
            wx.showToast({
              title: '扫重试01',
            })
          }
        });
      }
    }

  }, 5000);
  clearTimeout(scanTimoutTimer);

  wx.onBLEConnectionStateChange(function (res) { //链接状态回调
    console.log("连接状态" + res.connected, res);
    //蓝牙当前的连接状态
    getApp().globalData.devConnected = res ? res.connected : null;

    if (getApp().globalData._that.data.upgradeSuc != null) {
      console.log(getApp().globalData._that.data.upgradeSuc);
      getApp().globalData._that.data.upgradeSuc = null;
    }
    getApp().globalData._that.data.upgradeConnected = res.connected;
    if (!res.connected) {
      console.log("与设备断开");
      let lineNum = getApp().globalData.disconnectLineNum ? getApp().globalData.disconnectLineNum : '';
      util.recordLog(CONSTANT_DATA.err_type.monitor_blue_disconnect, "与设备断开:" + lineNum);
      getApp().clearTimeoutTimer();
      if (!lineNum) {
        BLELocker.disconnect('con297');
      }
    }
  });


  isScanTimeout = true;
  //搜索到的设备记录
  app.globalData.findDevs = new Array();
  let startScanTime = new Date().getTime();
  let findI = 0;
  console.log("onBluetoothDeviceFound调用:", mac)
  wx.onBluetoothDeviceFound(function (res) {
    console.log('搜到新设备监听事件',res)
    if (findI == 0) {
      clearTimeout(getApp().globalData.scanEquTimer);
      findI++;
    }

    var devices = res.devices;
    //判断搜索是否超时
    let curTime = new Date().getTime();
    //第一次超时5秒，重试一次8秒
    let scanTimeout = scanRetryCount == 1 ? 5000 : 8000;
    //超时且没有找到设备，防止连接超时同时造成搜索超时
    if (curTime - startScanTime > scanTimeout && isScanTimeout && !isFindDev) {
      isScanTimeout = false;
      //搜索超时，退出
      console.log("搜索超时退出------>", curTime, startScanTime);

      if (wx.canIUse('offBluetoothDeviceFound')) {
        wx.offBluetoothDeviceFound(function () {
          console.log("取消监听")
        });
      }

      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log("搜索停止成功,重试连接", mac);
          scanTimoutRetryCon(mac);
        },
        fail: function (err) {
          console.log("搜索停止失败,重试连接", mac);
          scanTimoutRetryCon(mac);
        }
      });

      getApp().hideLoading();

      //关闭已连接的设备，防止连接导致搜索不到设备
      wx.getConnectedBluetoothDevices({
        success: function (res) {
          console.log("蓝牙连接获取成功---->", res);
          let conDevices = res.devices;
          if (conDevices && conDevices.length > 0 && conDevices[0].deviceId) {
            console.log("存在连接的蓝牙---->");
            wx.closeBLEConnection({
              deviceId: conDevices[0].deviceId,
              success: function (res) {},
              fail: function (err) {},
              complete: function () {
                getApp().globalData.disconnectLineNum = "connect725";
              }
            });
          }
        },
        fail: function (err) {
          if (openBlueAdapterTimer) {
            clearTimeout(openBlueAdapterTimer);
          }
          console.log("蓝牙连接获取失败---->", err);
        }
      });

      return;
    }

    if (isFindDev) {
      if (isFindDevLog) {
        console.log("已找到设备")
      }
      isFindDevLog = false;


      if (wx.canIUse('offBluetoothDeviceFound')) {
        wx.offBluetoothDeviceFound(function () {
          console.log("取消监听")
        });
      }

      //找到设备后将重试次数标记恢复
      scanRetryCount = 1;
      //未发现任何设备的时候重试一次
      noFindOneRetryCount = 1;
      console.log("已搜索到设备")
      return;
    }

    if (devices == null || devices == undefined) {
      console.log("搜索的设备为空", res);
      return;
    }

    if (!app.globalData.isLeaseCon && isDfuFlg) {
      mac = dfuDevName;
    }
    if (devices.deviceId) {
      dev = findConDev(devices, mac);
      if (dev != null) {
        isScanTimeout = false;
        isFindDev = true;
        //匹配到设备可以关闭搜索
        console.log("匹配设备结束开始连接设备", dev, mac);
        if (app.globalData.isLeaseCon) {
          app.globalData._that.setData({
            loading_show: true,
            loading_desc: '设备已找到,连接中...',
            connectDesc: "设备已找到,连接中...",
          })
        }
        executeCon(dev, mac);

        if (wx.canIUse('offBluetoothDeviceFound')) {
          wx.offBluetoothDeviceFound(function () {
            console.log("取消监听")
          });
        }
        //找到设备后将重试次数标记恢复
        scanRetryCount = 1;
        //未发现任何设备的时候重试一次
        noFindOneRetryCount = 1;

        return;
      }
    }

    if (devices) {
      //查询设备列表是否存在要找的设备
      findDevFromScanDevices(devices, mac);
    }
    if (devices.devices) {
      //之前代码存在，但看文档不应该存在此种情况，为了程序健壮保留此判断
      findDevFromScanDevices(devices.devices, mac);
    }

  })

}

function findDevFromScanDevices(devices, mac) {
  //搜索到的蓝牙设备回调，对应可以将相关信息显示在界面上
  for (var i = 0; i < devices.length; i++) {
    var dev = null;
    if (!app.globalData.isLeaseCon && app.globalData.allowUpgradeOtherMac) {
      //允许升级旁边的控制盒
      if (!app.globalData.otherMacs || app.globalData.otherMacs.length == 0) {
        console.log("周围不存在控制盒------>");
        wx.stopBluetoothDevicesDiscovery({});
        getApp().hideLoading();
        return;
      }
      for (var j = 0; j < app.globalData.otherMacs.length; j++) {
        let otherMac = "DK" + app.globalData.otherMacs[j];
        dev = findConDev(devices[i], otherMac);
        if (dev != null) {
          console.log("搜到周围设备mac=", otherMac);
          //清空掉其他mac地址，防止重复的影响
          app.globalData.otherMacs = [];
          app.globalData.allowUpgradeOtherMac = false;
          mac = otherMac;
          break;
        }
      }
    } else {
      dev = findConDev(devices[i], mac);
    }

    if (dev != null) {
      isScanTimeout = false;
      isFindDev = true;
      //匹配到设备可以关闭搜索
      console.log("匹配设备结束开始连接设备", dev, mac);
      if (app.globalData.isLeaseCon) {
        app.globalData._that.setData({
          loading_show: true,
          loading_desc: '设备已找到,连接中...',
          connectDesc: "设备已找到,连接中...",
        })
      }
      executeCon(dev, mac);

      if (wx.canIUse('offBluetoothDeviceFound')) {
        wx.offBluetoothDeviceFound(function () {
          console.log("取消监听")
        });
      }

      scanRetryCount = 1;
      //未发现任何设备的时候重试一次
      noFindOneRetryCount = 1;

      break;
    }
  }
}

function executeCon(dev, mac) {
  if (app.globalData.isLeaseCon) {
    if(app.globalData.conTimeoutTimer) {
      clearTimeout(app.globalData.conTimeoutTimer)
    }    
    app.globalData.conTimeoutTimer = setTimeout(function () {
      if (!app.globalData.conIsSuc) {
        if(typeof app.globalData._that.getBleFailShowObj == 'function') {
          let bleFailShow = app.globalData._that.getBleFailShowObj()
          bleFailShow.modalMsgShow()
        }
        app.globalData._that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: '连接超时，请关闭蓝牙再打开后重试(Z' + app.globalData.curConHid + ')',
            desc_mini: CONSTANT_DATA.err_type.new_con_timeout,
            confirm: true
          }
        })
        colonyBlue.bleConFailMark();
      }
    }, 90000);
    //租赁连接
    console.log("租赁连接开始");
    app.globalData._that.setData({
      loading_show: true,
      loading_desc: '开始连接',
      connectDesc: "开始连接",
    })
    wx.getConnectedBluetoothDevices({
      success: function (res) {
        let conDevices = res.devices;
        if (conDevices && conDevices.length > 0 && conDevices[0].deviceId == dev.deviceId) {
          console.log("蓝牙已经连接---->");
          connectCmd.getSerciceAndNotify(dev, 100);
        } else {
          console.log("蓝牙未连接--开始连接", mac);
          connectCmd.connectLease(dev, mac, scanDevice);
        }
      },
      fail: function (err) {
        console.log("获取连接失败--开始连接", mac);
        connectCmd.connectLease(dev, mac, scanDevice);
      }
    })
  } else {
    if (mac != dfuDevName) {
      connetToDfu.connectDevice(dev, function () {
        upgradeDfu();
        if (getApp().globalData.isBeforeLeaseUpgrade) {
          wx.showLoading({
            title: '升级中..',
            mask: true
          });
        }
      });
    } else if (mac == dfuDevName) {
      isDfuFlg = false;
      dfuUpgrade.connectDfuDevice(dev, null);
    }
  }

}

//判断搜索到的设备是否为要找的设备
function findConDev(device, mac) {
  if (isFindDev) {
    //已找到设备
    console.log("已找到设备。。。", mac);
    isDfuFlg = false;
    return null;
  }

  let devName = null;
  //避免同一个设备多次重复回调
  if (device.name) {
    devName = device.name;
  } else if (device.localName) {
    devName = device.localName;
  }

  if (devName && app.globalData.findDevs.indexOf(devName) == -1) {
    app.globalData.findDevs.push(devName);
  }

  //蓝牙广播数据
  if (devName == mac) {
    console.log("【搜索到蓝牙设备】匹配到设备------》", device, advertisData, mac)
    return device;
  }

  //自定义广播数据
  let advertisData = device.advertisData ? ab2hex(device.advertisData) : null;
  if (advertisData) {
    let head = advertisData.substring(0, 4);
    if (head > 5701) {
      let adMacName = advertisData.substring(4, 16);
      let dname = 'DK' + adMacName.toUpperCase();

      let logDevName = "bc:" + dname;
      if (app.globalData.findDevs.indexOf(logDevName) == -1) {
        app.globalData.findDevs.push(logDevName);
      }

      if (mac === dname) {
        console.log("从自定义广播中匹配到mac", advertisData);
        return device;
      }
    }
    if (advertisData.length >= 16) {
      let devName = advertisData.substring(4, 6) + ":" + advertisData.substring(6, 8) + ":" + advertisData.substring(8, 10) + ":" + advertisData.substring(10, 12) + ":" + advertisData.substring(12, 14) + ":" + advertisData.substring(14, 16);
      devName = devName.toUpperCase();
      let logDevName = "bc:" + devName;
      if (app.globalData.findDevs.indexOf(logDevName) == -1) {
        app.globalData.findDevs.push(logDevName);
      }
      if (mac === devName) {
        console.log("从自定义广播中匹配到mac", advertisData, devName);
        return device;
      }
    }
  }

  return null;
}

//从缓存获取连接的设备信息
function getDevFromCacheByMac(mac) {
  if (mac) {
    let m = mac.indexOf("DK") == 0 ? mac.substring(2) : mac;
    return wx.getStorageSync(m);
  } else {
    return null;
  }
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  try {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
  } catch (ex) {
    return null;
  }
  return hexArr.join('');
}

function upgradeDfu() {
  isDfuFlg = true;
  app.globalData.allowUpgradeOtherMac = false;
  console.log("开始升级文件包..." + dfuDevName);
  //先关闭蓝牙适配器，成功失败均进行扫码连接
  wx.closeBluetoothAdapter({
    success: function (res) {
      console.log("关闭适配器成功..." + dfuDevName);
      scanDevice(dfuDevName);
    },
    fail: function (err) {
      console.log("关闭适配器失败..." + dfuDevName);
      scanDevice(dfuDevName);
    }
  });
}

function scanTimoutRetryCon(mac) {
  let errType = scanRetryCount == 1 ? CONSTANT_DATA.err_type.new_con_scan_timeout : CONSTANT_DATA.err_type.new_con_scan_second_timeout;
  let findDevsStr = JSON.stringify(app.globalData.findDevs);
  let isConFlg = getApp().globalData.devConnected;
  common.locationAddr(function(res){
    let err = res ? JSON.stringify(res) : "";
    util.recordLog(errType, "搜索超时:获取定位成功:" + mac + ":" + app.globalData.isLeaseCon + ":" + isAlreadyConnectedCount + ":" + scanRetryCount + ":" + findDevsStr + ":" + err + ":" + isConFlg);
  }, function(res){
    let err = res ? JSON.stringify(res) : "";
    util.recordLog(errType, "搜索超时:获取定位失败:" + mac + ":" + app.globalData.isLeaseCon + ":" + isAlreadyConnectedCount + ":" + scanRetryCount + ":" + findDevsStr + ":" + err + ":" + isConFlg);
  })

  wx.getConnectedBluetoothDevices({
    success: function (res) {
      let conDevices = res.devices;
      if (conDevices && conDevices.length > 0 && conDevices[0].deviceId) {
        console.log("存在连接的蓝牙---->");
        wx.closeBLEConnection({
          deviceId: conDevices[0].deviceId,
          success: function (res) {
            scanTimeoutRetryExcute(mac);
          },
          fail: function (err) {
            scanTimeoutRetryExcute(mac);
          },
          complete: function () {
            getApp().globalData.disconnectLineNum = "connect625";
          }
        });
      } else {
        scanTimeoutRetryExcute(mac);
      }
    },
    fail: function (err) {
      scanTimeoutRetryExcute(mac);
    }
  });
}

function scanTimeoutRetryExcute(mac) {
  if (scanRetryCount > 0) {
    setTimeout(function () {
      scanRetryCount--;
      startCon(mac);
    }, 200);
  } else {
    if(mac && mac.indexOf('DK') == 0) {
      mac = mac.substring(2)
    }
    conReq.getScanTimeoutTip(mac, function(tip){
      //搜索超时检查是否被其他人连接，若果被连接提示更换桩位
      if(tip && app.globalData._that) {
       app.globalData._that.setData({
         showScanTimeoutDialog: true,
         scanTimeoutTip: tip
       })
      }
    })
    //未搜索到任何设备关闭搜索，同时关闭蓝牙适配器
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {},
      complete: function () {
        wx.closeBluetoothAdapter({
          success: function (res) {},
        });
      }
    });

    let isIphone = app.globalData.platform ? app.globalData.platform.toLowerCase().indexOf("ios") == 0 : false;
    if(isIphone) {
      //苹果手机检查权限
      let checkRst = app.globalData._that.bleConAuthCheck(true)
      if (checkRst > 0) {
        //提示进行权限配置
        return
      }
    }
    
    colonyBlue.bleConFailMark();
    if (app.globalData._that) {
      if(typeof app.globalData._that.showFailTip == 'function') {
        app.globalData._that.showFailTip()
      }
      let pile_id = app.globalData._that.data.pile_id ? 'Z' + app.globalData._that.data.pile_id : '';
      console.log("系统信息----》", app.globalData.platform);
      let desc = !isIphone ? '请先关闭蓝牙和定位再重新打开后,微信扫码重试或换台设备重试' : '请关闭蓝牙再重新打开后，微信扫码重试或换台设备重试';
      let iconName = isIphone ? "" : "icon-dingwei";
      app.globalData._that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: '未搜索到设备' + pile_id + '(' + app.globalData._that.data.phoneInfo + "-" + CONSTANT_DATA.err_type.new_con_scan_timeout + ")",
          desc: desc,
          icon_name: iconName,
          desc_extra: isIphone ? '' : '点击“打开定位方法”可查看图示指引',
          retryConnect: true,
          open_location_show: !isIphone,
        }
      });

      
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '请先关闭蓝牙和定位再重新打开后,微信扫码重试或换台设备重试',
      })
    }
  }
}

function startCon(mac) {
  //连接重试1次
  app.globalData.conRetryTotalCount = 1;
  app.globalData.conRetryCount = app.globalData.conRetryTotalCount;
  console.log("开始新连接1.0....");
  openBlueAdapterTimer = setTimeout(function () {
    if (app.globalData.isLeaseCon) {
      let pile_id = app.globalData._that.data.pile_id ? 'Z' + app.globalData._that.data.pile_id : '';
      let desc = "请先关闭蓝牙,再打开蓝牙重试";
      if(typeof app.globalData._that.getBleFailShowObj == 'function') {
        let bleFailShow = app.globalData._that.getBleFailShowObj()
        bleFailShow.modalMsgShow()
      }
      app.globalData._that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: "BT无反应" + pile_id + '(' + app.globalData._that.data.phoneInfo + '-' + CONSTANT_DATA.err_type.new_conf_adapter_none + ')',
          desc: desc,
          retryConnect: true
        }
      });
    }
    wx.closeBluetoothAdapter({
      success: function (res) {},
    });
    util.recordLog(CONSTANT_DATA.err_type.new_conf_adapter_none, "打开适配器调用无反应:" + mac + ":" + app.globalData.isLeaseCon);
    colonyBlue.bleConFailMark();
  }, app.globalData._that.data.AdapterRespTime ? app.globalData._that.data.AdapterRespTime : _AdapterRespTime);
  
  //如果适配器已被开启
  if(app.globalData.conDevOpenBlueAdapterSuc === true) {
    console.log("适配器已被成功开启")
    if (openBlueAdapterTimer) {
      clearTimeout(openBlueAdapterTimer);
    }
    wx.removeStorageSync('retryOpenBlueAdapterCount');
    startScanMac(mac);
    return
  }

  wx.openBluetoothAdapter({
    success: function (res) {
      if (openBlueAdapterTimer) {
        clearTimeout(openBlueAdapterTimer);
      }
      wx.removeStorageSync('retryOpenBlueAdapterCount');
      startScanMac(mac);
    },
    fail: function (err) {
      common.clearConTimeCountTimer('865');
      let miniAuthSetting = app.globalData.miniAuthSetting
      let isAuthDeny = err && err.errMsg && err.errMsg.indexOf("openBluetoothAdapter:fail auth deny") != -1
      if ((miniAuthSetting != null && miniAuthSetting["scope.bluetooth"] === false) || isAuthDeny) {
        console.log("适配器打开失败，小程序未授权蓝牙")
        if (openBlueAdapterTimer) {
          clearTimeout(openBlueAdapterTimer);
        }
        // mark: 去配置小程序蓝牙权限设置
        if(conShowViewCallback != null) {
          conShowViewCallback('auth_mini_ble')
        }else {
          commonUtil.toSetMiniAuthSetting()
        }
        app.globalData._that.setData({
          loading_show: false
        })
        return
      }

      let retryOpenBlueAdapterCount = wx.getStorageSync('retryOpenBlueAdapterCount') || 0;
      wx.closeBluetoothAdapter({
        success: function (res) {},
        complete: function (res) {
          let adapterErrType = retryOpenBlueAdapterCount >= 2 ? CONSTANT_DATA.err_type.new_conf_open_adapter_fail_second : CONSTANT_DATA.err_type.new_conf_open_adapter_fail;
          let errInfo = err ? JSON.stringify(err) : "null";
          let closeRst = res ? JSON.stringify(res) : "closeNull";
          util.recordLog(adapterErrType, "适配器打开失败:" + errInfo + "#" + closeRst + ":" + app.globalData.isLeaseCon);
        }
      });
      app.globalData._that.data.openBlueAdapterFail = true;
      if (openBlueAdapterTimer) {
        clearTimeout(openBlueAdapterTimer);
      }
      if (app.globalData._that.data.retryConTimer) {
        clearTimeout(app.globalData._that.data.retryConTimer);
      }
      app.globalData._that.data.trying = false;
      console.log("蓝牙适配器打开失败,重试扫描连接", err, retryOpenBlueAdapterCount);
      let pile_id = app.globalData._that.data.pile_id ? 'Z' + app.globalData._that.data.pile_id : '';
      let desc = !err || err.state == 4 || err.errCode == 10001 ? "请打开蓝牙后重试" : "先关闭蓝牙,再打开蓝牙后重试";
      let descMini = !err || err.state == 4 || err.errCode == 10001 ? "BT未打开" : "BT未知异常";
      let desc_extra = '打开后才能进行租借';
      let retryConnect = !err || err.state == 4 || err.errCode == 10001;
      var isGatewayCon = app.globalData._that && colonyBlue.isGatewayCon(app.globalData._that) || app.globalData._that.data.hpIsColony == 2;
      if (err) {
        //小程序蓝牙是配置器不可用的错误码值
        colonyBlue.bleConFailMark();
        app.globalData.beforeConIsGateway = false;
        if (err.state == 1) {
          descMini = "BT重置中";
        } else if (err.state == 2) {
          descMini = "BT不支持";
        } else if (err.state == 3) {
          descMini = "BT未授权";
          desc = "请打开微信的蓝牙权限";
          desc_extra = '请根据蓝牙配置图示进行检查';
          retryConnect = false;
        } else {
          desc = "如果没有打开蓝牙请先打开蓝牙，再扫码；如果蓝牙已打开，请开关下蓝牙后再扫码";
        }
      }
      let systemInfo = app.globalData._that.data.systemInfo;
      let isIosFlg = false;
      if (systemInfo && ((systemInfo.model && systemInfo.model.toLowerCase().indexOf('iphone') != -1) || (systemInfo.brand && systemInfo.brand.toLowerCase().indexOf('iphone') != -1) || (systemInfo.system && systemInfo.system.toLowerCase().indexOf('ios') != -1))) {
        isIosFlg = true;
      }
      console.log("打开适配器失败后hpIsColony:", app.globalData._that.data.hpIsColony, isGatewayCon);
      if (isGatewayCon && !app.globalData.beforeConIsGateway) {
        let macAddr = mac.indexOf("DK") == 0 ? mac.substring(2) : mac;
        console.log("蓝牙适配器打开失败,直接走网关连接A,mac=", macAddr);
        colonyBlue.connectDev(macAddr, app.globalData._that);
        return;
      } else if (retryOpenBlueAdapterCount >= 2 && isIosFlg) {
        common.clearConTimeCountTimer(918)
        desc = "蓝牙配置出错";
        desc_extra = '请根据蓝牙配置图示进行检查';
        retryConnect = false;
        colonyBlue.bleConFailMark();
        app.globalData.beforeConIsGateway = false;
      } else {
        wx.setStorageSync('retryOpenBlueAdapterCount', retryOpenBlueAdapterCount);
        if (retryOpenBlueAdapterCount < 2) {
          retryOpenBlueAdapterCount += 1;
          wx.setStorageSync('retryOpenBlueAdapterCount', retryOpenBlueAdapterCount);
          //重试打开蓝牙
          app.globalData._that.setData({
            loading_show: true,
            loading_desc: '重新打开适配器中...',
            connectDesc: "重新打开适配器中...",
          })
          setTimeout(function () {
            startCon(mac);
          }, 500);

          colonyBlue.bleConFailMark();
          return;
        }
      }

      if(typeof app.globalData._that.getBleFailShowObj == 'function') {
        let bleFailShow = app.globalData._that.getBleFailShowObj()
        bleFailShow.modalMsgShow()
      }
      app.globalData._that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          icon_name: 'icon-lanya',
          desc_mini: descMini + pile_id + '(' + app.globalData._that.data.phoneInfo + '-' + CONSTANT_DATA.err_type.new_conf_open_adapter_fail + ')',
          desc: desc,
          desc_extra: desc_extra,
          retryConnect: retryConnect,
          open_ble_auth_show: !retryConnect,
        }
      });
    }
  })

}

function startScanMac(mac) {
  setTimeout(function () {
    scanDevice(mac);
  }, 100);
}

function setConShowViewCallback(callback) {
  conShowViewCallback = callback 
}

//蓝牙直连
function directBleCon(mac, devId) {
  //连接重试1次
  app.globalData.conRetryTotalCount = 1;
  app.globalData.conRetryCount = app.globalData.conRetryTotalCount;
  console.log("开始直连1.0....");
  openBlueAdapterTimer = setTimeout(function () {
    if (app.globalData.isLeaseCon) {
      let pile_id = app.globalData._that.data.pile_id ? 'Z' + app.globalData._that.data.pile_id : '';
      let desc = "请先关闭蓝牙,再打开蓝牙重试";
      if(typeof app.globalData._that.getBleFailShowObj == 'function') {
        let bleFailShow = app.globalData._that.getBleFailShowObj()
        bleFailShow.modalMsgShow()
      }
      app.globalData._that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: "BT无反应" + pile_id + '(' + app.globalData._that.data.phoneInfo + '-' + CONSTANT_DATA.err_type.new_conf_adapter_none + ')',
          desc: desc,
          retryConnect: true
        }
      });
    }
    wx.closeBluetoothAdapter({
      success: function (res) {},
    });
    util.recordLog(CONSTANT_DATA.err_type.new_conf_adapter_none, "打开适配器调用无反应-直连:" + mac + ":" + app.globalData.isLeaseCon);
  }, app.globalData._that.data.AdapterRespTime ? app.globalData._that.data.AdapterRespTime : _AdapterRespTime);
  
  wx.onBLEConnectionStateChange(function (res) { //链接状态回调
    console.log("连接状态direct:" + res.connected, res);
    //蓝牙当前的连接状态
    getApp().globalData.devConnected = res ? res.connected : null;

    if (getApp().globalData._that.data.upgradeSuc != null) {
      console.log(getApp().globalData._that.data.upgradeSuc);
      getApp().globalData._that.data.upgradeSuc = null;
    }
    getApp().globalData._that.data.upgradeConnected = res.connected;
    if (!res.connected) {
      console.log("与设备断开");
      let lineNum = getApp().globalData.disconnectLineNum ? getApp().globalData.disconnectLineNum : '';
      util.recordLog(CONSTANT_DATA.err_type.monitor_blue_disconnect, "与设备断开:" + lineNum);
      getApp().clearTimeoutTimer();
      if (!lineNum) {
        BLELocker.disconnect('con297');
      }
    }
  });
  
  let dev = {deviceId: devId}
  //如果适配器已被开启
  if(app.globalData.conDevOpenBlueAdapterSuc === true) {
    console.log("适配器已被成功开启-直连")
    if (openBlueAdapterTimer) {
      clearTimeout(openBlueAdapterTimer);
    }
    wx.removeStorageSync('retryOpenBlueAdapterCount');
    connectCmd.connectLease(dev, mac, scanDevice);
    return
  }

  wx.openBluetoothAdapter({
    success: function (res) {
      if (openBlueAdapterTimer) {
        clearTimeout(openBlueAdapterTimer);
      }
      wx.removeStorageSync('retryOpenBlueAdapterCount');
      connectCmd.connectLease(dev, mac, scanDevice);
    },
    fail: function (err) {
      common.clearConTimeCountTimer('865');
      let miniAuthSetting = app.globalData.miniAuthSetting
      let isAuthDeny = err && err.errMsg && err.errMsg.indexOf("openBluetoothAdapter:fail auth deny") != -1
      if ((miniAuthSetting != null && miniAuthSetting["scope.bluetooth"] === false) || isAuthDeny) {
        console.log("适配器打开失败，小程序未授权蓝牙")
        if (openBlueAdapterTimer) {
          clearTimeout(openBlueAdapterTimer);
        }
        // mark: 去配置小程序蓝牙权限设置
        if(conShowViewCallback != null) {
          conShowViewCallback('auth_mini_ble')
        }else {
          commonUtil.toSetMiniAuthSetting()
        }
        app.globalData._that.setData({
          loading_show: false
        })
        return
      }

      let retryOpenBlueAdapterCount = wx.getStorageSync('retryOpenBlueAdapterCount') || 0;
      wx.closeBluetoothAdapter({
        success: function (res) {},
        complete: function (res) {
          let adapterErrType = retryOpenBlueAdapterCount >= 2 ? CONSTANT_DATA.err_type.new_conf_open_adapter_fail_second : CONSTANT_DATA.err_type.new_conf_open_adapter_fail;
          let errInfo = err ? JSON.stringify(err) : "null";
          let closeRst = res ? JSON.stringify(res) : "closeNull";
          util.recordLog(adapterErrType, "适配器打开失败:" + errInfo + "#" + closeRst + ":" + app.globalData.isLeaseCon);
        }
      });
      app.globalData._that.data.openBlueAdapterFail = true;
      if (openBlueAdapterTimer) {
        clearTimeout(openBlueAdapterTimer);
      }
      if (app.globalData._that.data.retryConTimer) {
        clearTimeout(app.globalData._that.data.retryConTimer);
      }
      app.globalData._that.data.trying = false;
      console.log("蓝牙适配器打开失败,重试扫描连接", err, retryOpenBlueAdapterCount);
      let pile_id = app.globalData._that.data.pile_id ? 'Z' + app.globalData._that.data.pile_id : '';
      let desc = !err || err.state == 4 || err.errCode == 10001 ? "请打开蓝牙后重试" : "先关闭蓝牙,再打开蓝牙后重试";
      let descMini = !err || err.state == 4 || err.errCode == 10001 ? "BT未打开" : "BT未知异常";
      let desc_extra = '打开后才能进行租借';
      let retryConnect = !err || err.state == 4 || err.errCode == 10001;
      var isGatewayCon = app.globalData._that && colonyBlue.isGatewayCon(app.globalData._that) || app.globalData._that.data.hpIsColony == 2;
      if (err) {
        //小程序蓝牙是配置器不可用的错误码值
        colonyBlue.bleConFailMark();
        app.globalData.beforeConIsGateway = false;
        if (err.state == 1) {
          descMini = "BT重置中";
        } else if (err.state == 2) {
          descMini = "BT不支持";
        } else if (err.state == 3) {
          descMini = "BT未授权";
          desc = "请打开微信的蓝牙权限";
          desc_extra = '请根据蓝牙配置图示进行检查';
          retryConnect = false;
        } else {
          desc = "如果没有打开蓝牙请先打开蓝牙，再扫码；如果蓝牙已打开，请开关下蓝牙后再扫码";
        }
      }
      let systemInfo = app.globalData._that.data.systemInfo;
      let isIosFlg = false;
      if (systemInfo && ((systemInfo.model && systemInfo.model.toLowerCase().indexOf('iphone') != -1) || (systemInfo.brand && systemInfo.brand.toLowerCase().indexOf('iphone') != -1) || (systemInfo.system && systemInfo.system.toLowerCase().indexOf('ios') != -1))) {
        isIosFlg = true;
      }
      console.log("打开适配器失败后hpIsColony:", app.globalData._that.data.hpIsColony, isGatewayCon);
      if (isGatewayCon && !app.globalData.beforeConIsGateway) {
        let macAddr = mac.indexOf("DK") == 0 ? mac.substring(2) : mac;
        console.log("蓝牙适配器打开失败,直接走网关连接A,mac=", macAddr);
        colonyBlue.connectDev(macAddr, app.globalData._that);
        return;
      } else if (retryOpenBlueAdapterCount >= 2 && isIosFlg) {
        common.clearConTimeCountTimer(918)
        desc = "蓝牙配置出错";
        desc_extra = '请根据蓝牙配置图示进行检查';
        retryConnect = false;
        colonyBlue.bleConFailMark();
        app.globalData.beforeConIsGateway = false;
      } else {
        wx.setStorageSync('retryOpenBlueAdapterCount', retryOpenBlueAdapterCount);
        if (retryOpenBlueAdapterCount < 2) {
          retryOpenBlueAdapterCount += 1;
          wx.setStorageSync('retryOpenBlueAdapterCount', retryOpenBlueAdapterCount);
          //重试打开蓝牙
          app.globalData._that.setData({
            loading_show: true,
            loading_desc: '重新打开适配器中...',
            connectDesc: "重新打开适配器中...",
          })
          setTimeout(function () {
            startCon(mac);
          }, 500);

          colonyBlue.bleConFailMark();
          return;
        }
      }

      if(typeof app.globalData._that.getBleFailShowObj == 'function') {
        let bleFailShow = app.globalData._that.getBleFailShowObj()
        bleFailShow.modalMsgShow()
      }
      app.globalData._that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          icon_name: 'icon-lanya',
          desc_mini: descMini + pile_id + '(' + app.globalData._that.data.phoneInfo + '-' + CONSTANT_DATA.err_type.new_conf_open_adapter_fail + ')',
          desc: desc,
          desc_extra: desc_extra,
          retryConnect: retryConnect,
          open_ble_auth_show: !retryConnect,
        }
      });
    }
  })

}


module.exports = {
  scanDevice: scanDevice,
  upgradeDfu: upgradeDfu,
  startCon: startCon,
  directBleCon: directBleCon,
  setConShowViewCallback: setConShowViewCallback
}